package com.swa99ylum.pjv.bean;

import java.util.Arrays;
import java.util.Map;

import com.swa99ylum.pjv.corrector.Corrector;
import com.swa99ylum.pjv.validator.Validator;

public class JSONNode {
	
	private String nodeName;
	
	private Validator[] validators;
	private Corrector corrector;
	
	
	public JSONNode(String nodeName) {
		this(nodeName, new Validator[]{});
	}
	
	public JSONNode(String nodeName, Validator ... validators) {
		super();
		this.nodeName = nodeName;
		this.validators = validators;
	}
	

	@Override
	public String toString() {
		return "JSONNode [nodeName=" + nodeName + ", validators=" + Arrays.toString(validators) 
				+ ", corrector=" + corrector + "]";
	}
	
	/**
	 * 在 validators 的 头部 添加一个 validator
	 */
	public void unshiftValidator(Validator validator) {
		Validator[] validators2 = new Validator[validators.length+1];
		
		validators2[0] = validator;
		
		//数值拷贝 方式一
		System.arraycopy(validators, 0, validators2, 1, validators.length);
		
		//数值拷贝 方式二
//		for (int i=0; i<validators.length; i++) {
//			validators2[i+1] = validators[i];
//		}
		
		validators = validators2;
	}
	
	
	public void validate(Object rootObject, String[] nodePath, String nodeName, Map<String, Object> parentValue, Object incorrectValue) {
		//a) 如果没有 "验证器"，只有 "修正器"，则 直接执行 "修正器"
		if(validators.length == 0 && corrector!=null) {
			corrector.correct(rootObject, nodePath, nodeName, parentValue, incorrectValue);
		}
		
		//b) 如果有 "验证器"，则 只有当 任意一个 "验证器" 验证失败，才会去执行 "修正器"
		for (Validator validator : validators) {
			boolean result = validator.validate(rootObject, nodePath, nodeName, parentValue, incorrectValue);
			
			//只要有一个"验证器" 验证失败，就 直接执行 "修正器"（如果有的话），并终止 后续 "验证器"
			if(!result ) {
				if(corrector!=null) {
					corrector.correct(rootObject, nodePath, nodeName, parentValue, incorrectValue);
				}
				return;
			}
		}
		
	}

	
	/*--------------------------------------------
    |      			getter、setter		         |
    ============================================*/
	public String getNodeName() {
		return nodeName;
	}
	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}

	public Validator[] getValidators() {
		return validators;
	}
	public void setValidators(Validator[] validators) {
		this.validators = validators;
	}

	public Corrector getCorrector() {
		return corrector;
	}
	
	/** 链式构造器  */
	public JSONNode setCorrector(Corrector corrector) {
		this.corrector = corrector;
		return this;
	}
	
}
